package javacommon.base;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javacommon.util.ConvertRegisterHelper;
import javacommon.util.PageRequestFactory;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.Workbook;
import jxl.write.WritableWorkbook;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.RequestAware;
import org.springframework.util.Assert;

import cn.org.rapid_framework.beanutils.BeanUtils;
import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;
import cn.org.rapid_framework.util.ObjectUtils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.opensymphony.xwork2.ActionSupport;

import flex.messaging.util.URLEncoder;

@SuppressWarnings({ "serial", "rawtypes", "unchecked" })
public abstract class BaseStruts2Action extends ActionSupport implements RequestAware {
	protected Log log = LogFactory.getLog(getClass());

	protected final static String CREATED_SUCCESS = "创建成功";
	protected final static String UPDATE_SUCCESS = "更新成功";
	protected final static String DELETE_SUCCESS = "删除成功";
	protected final static String LOGIN_ERROR = "用户名或密码错误";

	// 返回Json数据格式的封装数据容器
	protected Map<String, Object> resultMap = new HashMap<String, Object>();
	protected int msgcode;
	protected String message;

	// 安全验证类型
	public enum CheckType {
		userIdAndDataId, // 验证用户id与数据类型是否一致
		userIdAndParentDataId // 根据用户和上一级数据id验证
	}

	protected Map requestMap = null;
	static {
		// 注册converters
		ConvertRegisterHelper.registerConverters();
	}

	public Map<String, Object> getResultMap() {
		return resultMap;
	}

	public int getMsgcode() {
		return msgcode;
	}

	public String getMessage() {
		return message;
	}

	public void copyProperties(Object target, Object source) {
		BeanUtils.copyProperties(target, source);
	}

	public <T> T copyProperties(Class<T> destClass, Object orig) {
		return BeanUtils.copyProperties(destClass, orig);
	}

	public void setRequest(Map request) {
		this.requestMap = request;
	}

	public void savePage(Page page, PageRequest pageRequest) {
		savePage("", page, pageRequest);
	}

	/**
	 * 用于一个页面有多个extremeTable是使用
	 * 
	 * @param tableId
	 *            等于extremeTable的tableId属性
	 */
	public void savePage(String tableId, Page page, PageRequest pageRequest) {
		Assert.notNull(tableId, "tableId must be not null");
		Assert.notNull(page, "page must be not null");

		getRequest().setAttribute(tableId + "page", page);
		getRequest().setAttribute(tableId + "totalRows", new Integer(page.getTotalCount()));
		getRequest().setAttribute(tableId + "pageRequest", pageRequest);
		getRequest().setAttribute(tableId + "query", pageRequest);
	}

	public <T extends PageRequest> T newQuery(Class<T> queryClazz, String defaultSortColumns) {
		PageRequest query = PageRequestFactory.bindPageRequest(
				org.springframework.beans.BeanUtils.instantiateClass(queryClazz), ServletActionContext.getRequest(),
				defaultSortColumns);
		return (T) query;
	}

	public <T extends PageRequest> T newQuery(Class<T> queryClazz) {
		PageRequest query = PageRequestFactory.bindPageRequest(
				org.springframework.beans.BeanUtils.instantiateClass(queryClazz), ServletActionContext.getRequest(),
				null);
		return (T) query;
	}

	public boolean isNullOrEmptyString(Object o) {
		return ObjectUtils.isNullOrEmptyString(o);
	}

	/**
	 * 获得当前登录用户
	 * 
	 * @return 当前登录用户
	 * @author ZhangGuodong
	 */
	public Object getLoginUserInfo() {
		return getSessionAttribute("acctUser");
	}

	/**
	 * 获得request对象
	 * 
	 * @return request对象
	 */
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 获得response对象
	 * 
	 * @return response对象
	 */
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 获得request中的参数
	 * 
	 * @param name
	 *            参数名称
	 * @return 参数名称对应的值
	 * @author ZhangGuodong
	 */
	public String getRequestParameter(String name) {
		return getRequest().getParameter(name);
	}

	public String[] getRequestParamterValues(String name) {
		return getRequest().getParameterValues(name);
	}

	/**
	 * 获得存放在request中的属性
	 * 
	 * @param name
	 *            属性名称
	 * @return 属性名称对应的值，如果返回null，代表属性名称不存在
	 * @author ZhangGuodong
	 */
	public Object getRequestAttribute(String name) {
		return getRequest().getAttribute(name);
	}

	/**
	 * 向request中存放属性
	 * 
	 * @param name
	 *            属性名称
	 * @param value
	 *            属性值
	 * @author ZhangGuodong
	 */
	public void setRequestAttribute(String name, Object value) {
		getRequest().setAttribute(name, value);
	}

	/**
	 * 获得session对象
	 * 
	 * @return session对象
	 * @author ZhangGuodong
	 */
	public HttpSession getSession() {
		return getRequest().getSession();
	}

	/**
	 * 获得存放在session对象中的属性
	 * 
	 * @param name
	 *            属性名称
	 * @return 属性名称对应的值，如果返回null，代表属性名称不存在
	 * @author ZhangGuodong
	 */
	public Object getSessionAttribute(String name) {
		return getRequest().getSession().getAttribute(name);
	}

	/**
	 * 向session对象中存放属性
	 * 
	 * @param name
	 *            属性名称
	 * @param value
	 *            属性值
	 * @author ZhangGuodong
	 */
	public void setSessionAttribute(String name, Object value) {
		getRequest().getSession().setAttribute(name, value);
	}

	/**
	 * 删除session对象中存放属性
	 * 
	 * @param name
	 *            属性名称
	 * @author ZhangGuodong
	 */
	public void removeSessionAttribute(String name) {
		getRequest().getSession().removeAttribute(name);
	}

	/**
	 * ajax 回写方法
	 * 
	 * @param str
	 * @author wanggq
	 */
	public void response(String str) {
		log.debug("response content:" + str);

		getResponse().setCharacterEncoding("UTF-8");
		getResponse().setContentType("application/xml");

		try {
			getResponse().getWriter().write(str);
			getResponse().getWriter().close();
		} catch (IOException e) {

		}
	}

	public void responseJson(String string) {
		log.debug("response content:" + string);

		getResponse().setCharacterEncoding("UTF-8");
		getResponse().setContentType("text/json");

		try {
			getResponse().getWriter().write(string);
			getResponse().getWriter().close();
		} catch (IOException e) {

		}
	}
	/**
	 * ajax回写方法
	 * 
	 * @param str
	 * @author ZhangGuodong
	 */
	public void response(StringBuilder str) {
		getResponse().setCharacterEncoding("UTF-8");
		getResponse().setContentType("application/xml");

		try {
			getResponse().getWriter().write(str.toString());
			getResponse().getWriter().close();
		} catch (IOException e) {

		}
	}

	public void writeHtml(Object obj) {
		write(obj, "text/html", false, "UTF-8");
	}

	public void writeJson(Object obj) {
		write(obj, "text/json", true, "UTF-8");
	}

	public void write(Object obj, String type, boolean jsonFormat, String encode) {
		HttpServletResponse response = getResponse();
		response.setCharacterEncoding(encode);
		response.setContentType(type);
		try {
			if (jsonFormat) {
				response.getWriter().write(JSONObject.toJSONString(obj, SerializerFeature.WriteMapNullValue));
			} else {
				response.getWriter().write(obj.toString());
			}
			response.getWriter().close();
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}

	/**
	 * 获得根路径
	 * 
	 * @return
	 */
	public String getBasePath() {
		String basePath = getRequest().getScheme() + "://" + getRequest().getServerName() + ":"
				+ getRequest().getServerPort() + getRequest().getContextPath() + "/";
		return basePath;
	}

	/**
	 * 根据域名返回不同参数，以加载不同资源文件
	 * 
	 * @author yaohl
	 * @returne
	 */
	public int getProduct() {
		String sn = getRequest().getServerName();
		if (sn.contains("ipinyou.com")) {
			return 1;
		} else if (sn.contains("mediacross.cn")) {
			return 2;
		} else if (sn.toLowerCase().contains("omgactivate.com")) {
			return 3;
		}
		return 0;
	}

	public String decode(String name) {
		String value = "";
		try {
			value = URLDecoder.decode(getRequestParameter(name), "utf-8");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return value;
	}

	public WritableWorkbook getWorkbook(String fileName) {
		WritableWorkbook book = null;
		try {
			HttpServletResponse response = getResponse();
			// response.setCharacterEncoding("utf-8");
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")
					+ ".xls");

			OutputStream os = response.getOutputStream();
			book = Workbook.createWorkbook(os);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return book;
	}

	public String getRealPath(String file) {
		ServletContext context = ServletActionContext.getServletContext();
		return context.getRealPath(file);
	}

	public Set<Long> getUserIds() {
		return (Set<Long>) getSessionAttribute("userIdSet");
	}
}
